package com.example.bijidemo.controller;

import com.example.bijidemo.common.R;
import com.example.bijidemo.common.SysLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件的上传与下载功能"
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class ConmmentController {

    @Value("${biji.path}")
    String basepath;
    //1.获取文件的名称找到文件的后缀名字
    @PostMapping("/upload")
   // @SysLog("图片的上传操作")
    public R<String> update(MultipartFile file){


        log.info(file.toString());
        String name = file.getOriginalFilename();
        int i = name.lastIndexOf(".");
        String namemate = name.substring(i);
        //2.通过文件吧文件的名称通过uuid生成
      String filename=  UUID.randomUUID().toString()+namemate;
        //3.创建文件的目录

        File dir=new File(basepath);

        if (!dir.exists()){
            boolean mkdir = dir.mkdir();
        }
        //4.吧临时文件转存到指定的位置
        try {
            file.transferTo(new File(basepath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(filename);
    }

    @GetMapping("download")
    //@SysLog("图片的下载回显到浏览器的操作")
    public void download(String name, HttpServletResponse response) {
      try {
          //输入流
          FileInputStream fileInputStream = new FileInputStream(new File(basepath + name));
          //输出流
          ServletOutputStream outputStream = response.getOutputStream();
          response.setContentType("image/jpeg");
          int i = 0;
          byte[] bytes = new byte[1024];
          while ((i = fileInputStream.read(bytes)) != -1) {
              outputStream.write(bytes, 0, i);
              outputStream.flush();
          }

          //关闭输入输出流
          outputStream.flush();
          fileInputStream.close();
      }catch (Exception ex){
          ex.printStackTrace();
      }

    }







}
